<?php
namespace Api\Model;

class AreaModel
{
    /**
     * 根目录parent_id
     * @var integer
     */
    private $parent_id = 0;
    /**
     * 获取所有区域
     * @return [type] [description]
     */
    public function getAll()
    {
        $area = S('area');
        if (!$area) {
            $area = M('area')
                ->order('id asc')
                ->select();
            S('area', $area);
        }

        return $area;
    }

    /**
     * 获取省
     * @return [type] [description]
     */
    public function getProvince()
    {
        $provinces = $this->getChilds($this->parent_id);
        return $provinces ? $provinces : [];
    }

    /**
     * 获取城市
     * @return [type] [description]
     */
    public function getCity($province_id)
    {
        $citys = $this->getChilds($province_id);
        return $citys ? $citys : [];
    }

    /**
     * 获取区县
     * @return [type] [description]
     */
    public function getRegion($city_id)
    {
        $regions = $this->getChilds($city_id);
        return $regions ? $regions : [];
    }

    /**
     * 获取子
     * @return [type] [description]
     */
    protected function getChilds($parent_id)
    {
        $childs = M('area')
            ->where([
                'parent_id' => $parent_id,
            ])
            ->order('id asc')
            ->select();
        return $childs ? $childs : [];
    }

    /**
     * 生成树分类
     * @param  string $categorys [description]
     * @return [type]            [description]
     */
    public function getTree($parent_id, $areas)
    {
        if (!count($areas)) {
            return false;
        }

        $res = [];
        foreach ($areas as $key => $area) {
            if ($area['parent_id'] == $parent_id) {
                unset($areas[$key]);
                $area['child'] = $this->getTree($area['id'], $areas);
                $res[]         = $area;
            }
        }
        return $res ? $res : [];
    }

    /**
     *获取所有区域
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getAllTree()
    {
        $areas     = $this->getAll();
        $parent_id = $this->parent_id;

        $area = $this->getTree($parent_id, $areas);

        return $area ? $area : [];
    }
}
